package com.huifai.common.utils;

import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * <br>==========================
 * <br> 创建人：吴传军
 * <br> 创建时间：2019/9/23 17:48
 * <br> 版本：1.0
 * <br> 描述：md5工具类
 * <br>==========================
 */
public class MD5Util {
    public MD5Util() {
    }

    public static final String MD5(String signature, String encode) throws RuntimeException {
        if (signature == null) {
            return null;
        } else {
            MessageDigest md5 = null;

            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException var7) {
                throw new RuntimeException("加密算法错误");
            }

            String ret = null;
            Object var4 = null;

            byte[] plainText;
            try {
                if (StringUtils.isEmpty(encode)) {
                    plainText = signature.getBytes();
                } else {
                    plainText = signature.getBytes(encode);
                }
            } catch (UnsupportedEncodingException var6) {
                throw new RuntimeException("MD5加密异常", var6);
            }

            md5.update(plainText);
            ret = bytes2HexString(md5.digest());
            return ret;
        }
    }

    public static String MD5(String key) {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        try {
            byte[] btInput = key.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;

            for(int i = 0; i < j; ++i) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 15];
                str[k++] = hexDigits[byte0 & 15];
            }

            return new String(str);
        } catch (Exception var10) {
            return null;
        }
    }

    public static String bytes2HexString(byte[] bytes) {
        String hs = "";
        if (bytes != null) {
            byte[] var5 = bytes;
            int var4 = bytes.length;

            for(int var3 = 0; var3 < var4; ++var3) {
                byte b = var5[var3];
                String tmp = Integer.toHexString(b & 255);
                if (tmp.length() == 1) {
                    hs = hs + "0" + tmp;
                } else {
                    hs = hs + tmp;
                }
            }
        }

        return hs;
    }

    public static void main(String[] args) {
        String jiami = MD5("admin");
        System.out.println(jiami);
    }
}
